import axios from 'axios'
import ElementUI from 'element-ui'
import { MessageBox, Message, Loading } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
var loadingInstance = null
function startLoading() {
  loadingInstance = Loading.service({
    fullscreen: true,
    text: '接口请求中...',
    customClass: 'common-loading'
  })
}
function endLoading() {
  if (loadingInstance) {
    loadingInstance.close()
  }
}
const service = axios.create({
  baseURL: process.env.NODE_ENV === 'development' ? process.env.VUE_APP_BASE_API : window.g.baseURL,
  timeout: 5000
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    var loading = true
    if (config.method === 'get') {
      if (config.params != null) {
        if (config.params.loading != null) {
          loading = config.params.loading
        }
      }
      config.params = {
        _t: Date.parse(new Date()) / 1000,
        ...config.params
      }
    }
    if (config.method === 'post') {
      if (config.data != null) {
        if (config.data instanceof FormData) {
          if (config.data.has('loading')) {
            loading = config.data.get('loading')
          }
        }
        if (config.data.loading != null) {
          loading = config.data.loading
        }
      }
    }
    if (loading) {
      startLoading()
    }
    if (store.getters.token) {
      config.headers['Access-Token'] = getToken()
    }
    return config
  },
  error => {
    console.log(error) // for debug
    endLoading()
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    endLoading()
    const res = response.data
    var { responseType } = response.request
    console.log(responseType)
    switch (responseType) {
      case 'arraybuffer':
        var resultBufferString = String.fromCharCode.apply(null, new Uint8Array(res))
        if (resultBufferString.toLocaleLowerCase().indexOf('png') > -1 || resultBufferString.toLocaleLowerCase().indexOf('jfif') > -1) {
          return 'data:image/png;base64,' + btoa(new Uint8Array(res).reduce((data, byte) => data + String.fromCharCode(byte), ''))
        } else {
          resultBufferString = decodeURIComponent(escape(resultBufferString))
          resultBufferString = JSON.parse(resultBufferString)
          Message({
            message: resultBufferString.data == null ? resultBufferString.message : resultBufferString.data,
            type: 'warning',
            duration: 5 * 1000
          })
        }
        break
      default:
        if (res.code !== 200) {
          if (res.code === 501) {
            var html = ''
            var data = res.data
            for (var item in data) {
              html += `【${item}】<m style="color:red">${data[item]}</m><br>`
            }
            ElementUI.Notification({
              type: 'warning',
              title: res.message,
              dangerouslyUseHTMLString: true,
              duration: 10 * 1000,
              message: `<div>${html}</div>`
            })
          } else if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
            MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
              confirmButtonText: 'Re-Login',
              cancelButtonText: 'Cancel',
              type: 'warning'
            }).then(() => {
              store.dispatch('user/resetToken').then(() => {
                location.reload()
              })
            })
          } else {
            Message({
              message: res.data ? res.data : (res.message || 'Error'),
              type: 'error',
              duration: 5 * 1000
            })
          }
          return Promise.reject(new Error(res.message || 'Error'))
        } else {
          return res.data
        }
    }
  },
  error => {
    endLoading()
    console.error('err' + error)
    Message({
      message: error.message === 'Network Error' ? '抱歉,服务忙,请稍后重试~' : error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)
/**
 * GET请求包装
 */
service.get = (url, params = {}) => {
  return service({
    method: 'GET',
    url: url,
    params: params
  })
}

/**
 * POST请求包装
 */
service.post = (url, params = {}) => {
  return service({
    method: 'POST',
    url: url,
    data: params,
    headers: {
      'Content-Type': 'application/json;charset=UTF-8'
    }
  })
}

/**
 * 图片流包装
 */
service.pictureStream = (url, params) => {
  return service({
    method: 'GET',
    url: url,
    params: params,
    responseType: 'arraybuffer'
  })
}
/**
 * 导出请求包装
 */
service.exportData = (url, params) => {
  return service({
    method: 'POST',
    url: url,
    data: params,
    responseType: 'blob',
    headers: {
      'Content-Type': 'application/json;charset=UTF-8'
    }
  })
}

service.fileUpload = (url, params) => {
  return service({
    method: 'POST',
    url: url,
    data: params,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}
export default service
